package com.wanmait.employment.manageController;


import com.wanmait.employment.entity.Admin;
import com.wanmait.employment.service.AdminService;
import com.wanmait.employment.util.AjaxResult;
import com.wanmait.employment.util.ImageUtils;
import com.wanmait.employment.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("manage")
public class    LoginController {
    @Resource
    private AdminService adminService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("login")
    public AjaxResult login(@RequestBody Admin admin, HttpSession session,
                            @RequestParam("code")String code) {

        String code2 = (String) session.getAttribute("code");
        if (code2!=null && code2.equalsIgnoreCase(code)) {
            Admin admin1 = adminService.login(admin);
            if (admin1 == null) {
                return AjaxResult.error(10001, "登录失败");
            } else {
                Map<String, String> claims = new HashMap<>();
                claims.put("admin_name", admin.getAdminName());
                String token = JWTUtils.createToken(admin1.getId() + "", 1800, admin1.getAdminPass(), claims);
                redisTemplate.opsForValue().set("token"+token,admin1,1800, TimeUnit.MINUTES);
                //放到数据库中，有效期和token的一致
                admin1.setAdminPass(null);
                return AjaxResult.success("登录成功").put("token", token).put("admin", admin1);
            }
        } else {
             return AjaxResult.error(10003,"验证码错误");
        }
    }



    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response,HttpSession session) throws IOException {
        HashMap<String,Object> map= ImageUtils.getImage();
        BufferedImage bi=(BufferedImage) map.get("bi");
        String code=(String)map.get("code");
        session.setAttribute("code",code);
        ImageIO.write(bi,"jpg",response.getOutputStream());
    }


}

